package com.yin.myproject.thread;

import java.util.concurrent.CyclicBarrier;

/**
 * @author Eason
 * @create 2018-03-22 15:29
 **/
public class CyclicBarrierUsecase {
    private CyclicBarrier barrier = new CyclicBarrier(5, new Runnable(){
        @Override
        public void run() {
            System.out.println("Callback is running");
        }
    });

    public void race() throws Exception{
        System.out.println("Thread " + Thread.currentThread().getName() + " is waiting the resource");
        barrier.await();
        System.out.println("Thread " + Thread.currentThread().getName() + " got the resource");
    }

    public static void main(String[] args){
        final CyclicBarrierUsecase usecase = new CyclicBarrierUsecase();
        for(int i = 0; i < 12; i++){
            Thread t = new Thread(() -> {
                try {
                    usecase.race();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }, String.valueOf(i));
            t.start();
        }
    }
}
